"""Definition of request handlers for the application.
"""
__author__ = 'Christopher James Calo'

from google.appengine.ext.webapp import RequestHandler
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
import logging
import os
import models

def render(context):
  path = os.path.join(os.path.dirname(__file__), 'templates/charmap.html')
  return template.render(path, context)

class Charmap(RequestHandler):
  MAX_RESULTS = 20
  CACHE_LENGTH = 604800 # 7 days
  
  def get(self):
    """Renders the character map view.
    """
    query = self.request.get('chq')
    logging.info('Query: %s' % query)
    cache = memcache.Client()
    chars = cache.get(query)
    logging.debug('Checked memcache for query %s' % query)
    if not chars:
      logging.debug('Checking datastore for query %s' % query)
      chars = models.UnicodeChar.all().search(query).fetch(self.MAX_RESULTS)
      logging.debug('%d records fetched' % len(chars))
      logging.debug('Adding to cache for 7 days')
      cache.add(query, chars, self.CACHE_LENGTH)
    self.response.out.write(render(locals()))

class TestRunner(RequestHandler):
  # TODO: move the TestRunner handler to app.yaml
  def get(self):
    import unittest, apptests
    self.response.headers['Content-Type'] = 'text/plain'
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    suite.addTest(loader.loadTestsFromModule(apptests))
    runner = unittest.TextTestRunner(self.response.out)
    runner.run(suite)